package com.itheima.controller;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: CommonController
 * @Description:
 * @Author: zhangcheng
 * @DateTime: 2022/6/8 18:49
 * @Version 1.0
 */

@Transactional
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.path}")
    private String basepath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //此时file是临时文件,需要设置转存地址
        log.info(file.toString());
        //原始文件名
        String originalFilename = file.getOriginalFilename(); //abc.jpg
        //获得后缀  .jpg
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用uuid重新生成文件名称,防止文件名重复,造成文件覆盖
        String fileName = UUID.randomUUID().toString() + substring;
        //判断上传目录是否存在
        File dir = new File(basepath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basepath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            response.setContentType("image/jpeg");
            FileInputStream is = new FileInputStream(new File(basepath, name));
            ServletOutputStream os = response.getOutputStream();
            IOUtils.copy(is,os);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
